package com.zheng.study.company.service.impl;

import com.zheng.study.base.bean.BaseEnumManager;
import com.zheng.study.base.bean.Result;
import com.zheng.study.base.bean.search.SearchEnum;
import com.zheng.study.base.bean.search.order.Order;
import com.zheng.study.base.bean.search.page.PagePaging;
import com.zheng.study.base.bean.search.result.SearchResultList;
import com.zheng.study.base.bean.search.result.SearchResultPaging;
import com.zheng.study.base.bean.search.rule.Rule;
import com.zheng.study.base.bean.search.rule.RuleHelper;
import com.zheng.study.base.dao.BaseDao;
import com.zheng.study.base.service.impl.BaseServiceImpl;
import com.zheng.study.company.dao.DutyDao;
import com.zheng.study.company.entity.Department;
import com.zheng.study.company.entity.Duty;
import com.zheng.study.company.entity.Power;
import com.zheng.study.company.entity.User;
import com.zheng.study.company.service.DutyService;
import com.zheng.study.company.service.PowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * newFile
 * ============================================================================
 * author : dzw
 * createDate:  2018/11/13 。
 * ============================================================================
 */
@Service
public class DutyServiceImpl extends BaseServiceImpl<Duty, String> implements DutyService {

	@Autowired
	private DutyDao dutyDao;
	@Autowired
	private PowerService powerService;

	@Override
	public BaseDao<Duty, String> getBaseDao() {
		return dutyDao;
	}

	@Override
	public SearchResultPaging getDutyPageByDept(PagePaging page, List<Rule> rules, Order order, Department department) {
		if(rules==null) rules = new ArrayList<Rule>();
		if(department!=null) rules.add(RuleHelper.eq("power.department", department));
		rules.add(RuleHelper.eq("state", BaseEnumManager.StateEnum.Enable));

		if(order==null) order = Order.order("user.pinYinHead", SearchEnum.OrderType.asc);
		return findPagingBySearch(page, rules, order);
	}

	@Override
	public List<Duty> getUserDutyList(User user) {
		return dutyDao.getUserDutyList(user);
	}

	@Override
	public Result saveUserDutyList(User user, List<Power> newPowerList) {
		List<Duty> oldDutyList = getUserDutyList(user); //原来的职责列表
		List<Power> oldPowerList = powerService.getPowerListByUser(user); //原来的职权列表

		//删除去掉的职责
		for(Duty duty:oldDutyList){
			Power power = duty.getPower();
			if(!newPowerList.contains(power)){
				duty.setState(BaseEnumManager.StateEnum.Delete);
				update(duty);
			}
		}

		//添加新增的职责
		for(Power power:newPowerList){
			if(!oldPowerList.contains(power)){
				Duty duty = new Duty(user, power);
				save(duty);
			}
		}

		return resultService.success();
	}

	@Override
	public Duty getDutyByUserAndPower(User user, Power power) {
		return dutyDao.getDutyByUserAndPower(user, power);
	}
}
